#include "Window.hpp"

#include <stdexcept>

namespace icecode {
  namespace graphics {

    Window::Window(icecode::graphics::XConnection& conn, std::string title, unsigned int width, unsigned int height) : x(conn)
    {
      ::XSetWindowAttributes att = {0};

      if (width < 1) width = 1;
      if (height < 1) height = 1;

      att.background_pixel = BlackPixel(x.getDisplay(), x.getScreenNumber());
      att.border_pixel = WhitePixel(x.getDisplay(), x.getScreenNumber());
      att.backing_store = NotUseful;
      att.event_mask = KeyPressMask | KeyReleaseMask | ButtonPressMask | ButtonReleaseMask | StructureNotifyMask | FocusChangeMask;
      att.override_redirect = False;

      id = ::XCreateWindow(x.getDisplay(), RootWindow(x.getDisplay(), x.getScreenNumber()), 10, 10, width, height, 1, CopyFromParent, InputOutput, CopyFromParent, CWBackPixel | CWBorderPixel | CWBackingStore | CWEventMask | CWOverrideRedirect, &att);

      if(!id)  { // Error
	throw std::runtime_error("Unable to create window");
      }

      ::XStoreName(x.getDisplay(), id, title.c_str());

      //TODO: GL init

    }

    void Window::close()
    {
      ::XDestroyWindow(x.getDisplay(), id);
    }

    void Window::setVisible(bool _show)
    {
      if(_show)
	::XMapRaised(x.getDisplay(), id);
      else
	::XUnmapWindow(x.getDisplay(), id);
    }

    void Window::setSize(unsigned int width, unsigned int height)
    {
      ::XResizeWindow(x.getDisplay(), id, width, height);
    }

    std::array<unsigned int, 2> Window::getSize()
    {
      std::array<unsigned int, 2> a;
      //register unsigned int w, h;
      int x, y;
      ::Window root;
      unsigned int border, depth;

      ::XGetGeometry(this->x.getDisplay(), id, &root, &x, &y, &a[0], &a[1], &border, &depth);
      //a[0] = w;
      //a[1] = h;
      return a; //TODO: Remove unuseful commented code
    }

  }
}
